package fudan.se.project.util.user;


import fudan.se.project.domain.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Gao Longchao
 */
@Component
public class UserDetailsUtil {

    public User currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) return null;
        Object principal = authentication.getPrincipal();
        if (principal instanceof User) {
            return (User) principal;
        }
        return null;
    }

    public String currentUsername() {
        User user = currentUser();
        return user == null ? null : user.getUsername();
    }

    public Collection<? extends GrantedAuthority> systemAuthorities() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) return new ArrayList<>(0);
        return authentication.getAuthorities();
    }

}
